
//   CODE WRITTEN BY AI


// Bubble sort demonstration
// Sort five integers from smallest to largest

// --------------------------------------------------
// Store the original array in memory
// --------------------------------------------------

start:
addi x1, x0, 42
sw   x1, 0(x0)

addi x1, x0, 17
sw   x1, 4(x0)

addi x1, x0, 68
sw   x1, 8(x0)

addi x1, x0, 9
sw   x1, 12(x0)

addi x1, x0, 31
sw   x1, 16(x0)

// --------------------------------------------------
// Display the original array
// --------------------------------------------------

cout << "BUBBLE SORT DEMONSTRATION" << endl;
cout << endl;
cout << "Original values:" << endl;

lw   x1, 0(x0)
cout << x1 << endl;

lw   x1, 4(x0)
cout << x1 << endl;

lw   x1, 8(x0)
cout << x1 << endl;

lw   x1, 12(x0)
cout << x1 << endl;

lw   x1, 16(x0)
cout << x1 << endl;

// --------------------------------------------------
// Bubble sort
// --------------------------------------------------

// x10 = number of outer passes
// x11 = number of comparisons in current pass
// x12 = current memory address
// x13 = left value
// x14 = right value

addi x10, x0, 4       // Four sorting passes

outer_loop:
add  x11, x10, x0     // Comparisons needed this pass
addi x12, x0, 0       // Begin at memory address 0

inner_loop:
lw   x13, 0(x12)      // Load left value
lw   x14, 4(x12)      // Load right value

bge  x14, x13, no_swap // No swap if right >= left

sw   x14, 0(x12)      // Store smaller value on left
sw   x13, 4(x12)      // Store larger value on right

no_swap:
addi x12, x12, 4      // Move to next array position
addi x11, x11, -1     // One comparison completed
bne  x11, x0, inner_loop

addi x10, x10, -1     // One pass completed
bne  x10, x0, outer_loop

// --------------------------------------------------
// Display the sorted array
// --------------------------------------------------

cout << endl;
cout << "Sorted values:" << endl;

lw   x1, 0(x0)
cout << x1 << endl;

lw   x1, 4(x0)
cout << x1 << endl;

lw   x1, 8(x0)
cout << x1 << endl;

lw   x1, 12(x0)
cout << x1 << endl;

lw   x1, 16(x0)
cout << x1 << endl;

cout << endl;
cout << "SORT COMPLETE" << endl;
